package com.dk.shiro;


import com.dk.pojo.Menu;
import com.dk.pojo.TPerson;
import com.dk.service.MenuService;
import com.dk.service.PersonService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ShiroRealm extends AuthorizingRealm {

    @DubboReference
    private PersonService personService;

    @DubboReference
    private MenuService menuService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        System.out.println("进入授权方法");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

      /*  List<String> list = new ArrayList<>();

        list.add("a-delete");

        ;*/

        Subject subject = SecurityUtils.getSubject();

        TPerson tPerson =(TPerson) subject.getPrincipal();

        List<String> list = menuService.selectPermsById(tPerson.getPid());

        info.addStringPermissions(list);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        System.out.println("进入认证方法");


        //获取token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        String username = token.getUsername();
        //根据用户名判断是否存在
        TPerson person = personService.selectInfo(username);
        //等于null,说明用户不存在
        if (person == null){

            return null;
        }

        //1.登陆成功后用户存到session
        //2.数据库密码
        //3.盐
        //4.登陆成功后用户的账户名
        return new SimpleAuthenticationInfo(person,person.getPwd(), ByteSource.Util.bytes(person.getSalt()),"admin");
    }
}
